package com.vcredit.creditcat.web.api.product;

import com.fasterxml.jackson.core.type.TypeReference;
import com.vcredit.creditcat.utils.Base64Utils;
import com.vcredit.creditcat.utils.GZIPUtils;
import com.vcredit.creditcat.utils.RSAUtils;
import com.vcredit.creditcat.vo.payday.CommonRequest;
import com.vcredit.creditcat.vo.payday.CommonResponse;
import com.vcredit.creditcat.vo.payday.ParamRequest;
import com.vcredit.framework.annotation.Log;
import com.vcredit.framework.util.HttpRequest;
import com.vcredit.framework.util.JacksonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("api-test")
public class PayDayProductRequestController {

	private static final Logger LOG = LoggerFactory.getLogger(PayDayProductResponseController.class);

	// 合作方公钥
	@Value("${request.parent.publicKey}")
	private String publicKey;
	// 信用猫私钥
	@Value("${request.xinyongmao.privateKey}")
	private String privateKey;

	//准入接口
	@Log
	@RequestMapping("/request")
	@ResponseBody
	public Object userAccess(@RequestBody ParamRequest param)
			throws Exception {
		try {
			StringBuffer log=new StringBuffer();
			String ac_name = param.getAc_name();
			if(StringUtils.isEmpty(ac_name) || param.getBiz_data() == null) {
                return new CommonResponse().Failure("入参错误!");
			}

			CommonRequest request = new CommonRequest().init();

			Object bidData = param.getBiz_data();
			request.setBiz_data(bidData);

			//1、先判断是否需要压缩业务数据进行压缩操作
			if(ac_name.equals("addressbook/commit") || ac_name.equals("phone/commit")) {
				//这两个接口进行biz_data数据压缩
				request.setIs_compress(1);
			}

			//2、信用猫使用合作方平台的RSA公钥对业务参数进行RSA加密
			String compressBizData = JacksonUtil.Obj2Json(request.getBiz_data());
			byte[] data = compressBizData.getBytes("UTF-8");
			byte[] encodedData = RSAUtils.encryptByPublicKey(data, publicKey);
            String base64encodedData =  Base64Utils.encode(encodedData);
            System.out.println("压缩前业务数据字符串：" + base64encodedData);
			log=log.append("压缩前业务数据字符串：" + base64encodedData).append("\r\n");
			request.setBiz_data(base64encodedData);
            //3、如果需要压缩,在加密完成后做业务数据压缩
            if(request.getIs_compress()==1) {
                System.out.println("原长度：" + base64encodedData.length());
                System.out.println("压缩后字符串长度：" + GZIPUtils.compress(base64encodedData).toString().length());
                System.out.println("压缩后字符串：" + GZIPUtils.compress(base64encodedData).toString());
				log=log.append("原长度：" + base64encodedData.length()).append("\n");
				log=log.append("压缩后字符串长度：" + GZIPUtils.compress(base64encodedData).toString().length()).append("\n");
				log=log.append("压缩后字符串：" + GZIPUtils.compress(base64encodedData).toString()).append("\n");
                request.setBiz_data(Base64Utils.encode(GZIPUtils.compress(base64encodedData)));
            }

			//4、使用信用猫自己的RSA私钥对所有参数进行签名
			String requsetJson = JacksonUtil.Obj2Json(request);
			byte[] requestData = requsetJson.getBytes("UTF-8");
			String sign = RSAUtils.sign(requestData, privateKey);
			request.setSign(sign);

			System.out.println("网络传输前请求内容: \r\n" + JacksonUtil.Obj2Json(request));
			log=log.append("网络传输前请求内容：" + JacksonUtil.Obj2Json(request)).append("\n");

			//String queryResultStr = HttpRequest.doJson("http://localhost:7002/api/response", JacksonUtil.Obj2Json(request), 20000);

			String queryResultStr = HttpRequest.doJson("http://123.57.8.174:43896/payday-loan-core/api/"+ac_name, JacksonUtil.Obj2Json(request), 20000);

			System.out.println(queryResultStr);
			if(!StringUtils.isEmpty(queryResultStr)) {
				CommonResponse resultData=JacksonUtil.Json2Obj(queryResultStr, new TypeReference<CommonResponse>() {
				});
				log=log.append(resultData.getLog());
				CommonResponse result=new CommonResponse().Success();
				result.setData(resultData.getData());
				result.setLog(log.toString());
				return result;
			}
			return new CommonResponse().Failure("未知错误");
		} catch (Exception ex) {
			return new CommonResponse().Failure("未知错误");
		}
	}
}
